var main = angular.module('main');

main.controller('loginCtrl', ['$scope', 'http', '$state', function($scope, http, $state) {
    $scope.userNameError = false;
    $scope.passwordError = false;
    $scope.userName = '';
    $scope.password = '';
    $scope.checkUsername = function() {
        var username = $scope.userName;
        if (!(username.length >= 6 && username.length <= 18)) {
            $scope.userNameError = true;
            $scope.usernameErrorMsg = '用户名长度不正确';
            return false;
        }
        if (!$scope.userName.match(/^[a-zA-Z0-9_]+$/)) {
            $scope.userNameError = true;
            $scope.usernameErrorMsg = '用户名格式不正确';
            return false;
        }
        $scope.userNameError = false;
        return true;
    };
    $scope.checkPassword = function() {
        var password = $scope.password;
        if (!(password.length >= 6 && password.length <= 18)) {
            $scope.passwordError = true;
            $scope.passwordErrorMsg = '密码长度不正确';
            return false;
        }
        if (!$scope.password.match(/^[a-zA-Z0-9_]+$/)) {
            $scope.passwordError = true;
            $scope.passwordErrorMsg = '密码格式不正确';
            return false;
        }
        $scope.passwordError = false;
        return true;
    };
    $scope.login = function() {
        if ($scope.checkUsername() && $scope.checkPassword()) {
            var result = http.post('/user/login', { username: $scope.userName, password: $scope.password });
            result.then(function(data) {
                if (data.code === 0) {
                    Cookies.set('user_id', data.data.user_id);
                    Cookies.set('token', data.data.token);
                    $state.go('project.projects', { 'type': 'allProject' });
                }

            }, function(error) {
                console.log(error);
            });
        }
    };
}]);